const cloud = require('wx-server-sdk')
const md5 = require('js-md5')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  var name=event.name
  var totalFee=event.totalFee
  var nickName=event.nickName
  var outTradeNo=md5(new Date().getTime()+wxContext.OPENID)

  if(nickName){
    const addUserResult = await db.collection("tradeOrder").add({
      data: {
        outTradeNo: outTradeNo,
        openId: wxContext.OPENID,
        totalFee:totalFee,
        nickName:nickName
      }
    })
    console.log("addUserResult" + JSON.stringify(addUserResult))
    if (addUserResult.errMsg == "collection.add:ok") {
  
    }
  }
  
  const res = await cloud.cloudPay.unifiedOrder({
    "body" : name,
    "outTradeNo" : outTradeNo,
    "spbillCreateIp" : "127.0.0.1",
    "subMchId" : "1523278261",
    "totalFee" : totalFee,
    "envId": "takeaway-lpus8",
    "functionName": "unifiedOrder"
  })
  return {result:res,outTradeNo}
}